#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Common.hpp"


int main(int argc, char* argv[])
{
    //获取服务器信息
    if(argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " <server_ip> <server_port>" << std::endl;
        return 1;
    }
    std::string ser_ip = argv[1];
    int ser_port = std::stoi(argv[2]);

    //创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket err" << std::endl;
        return 2;
    }

    struct sockaddr_in ser_addr;
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(ser_port);
    ser_addr.sin_addr.s_addr = inet_addr(ser_ip.c_str());

    int n = connect(sockfd, CONV(&ser_addr), sizeof(ser_addr));
    if(n < 0)
    {
        std::cerr << "connect err" << std::endl;
        return 3;
    }

    //循环发送接收逻辑
    std::string message;
    while(true)
    {
        char serbuff[1024];
        std::cout << "send message# ";
        // std::cin >> message;
        std::getline(std::cin, message);

        //发送数据
        n = ::send(sockfd, message.c_str(), message.size(), 0);
        if(n < 0)
        {
            std::cerr << "send err" << std::endl;
            break;
        }

        n = ::recv(sockfd, serbuff, sizeof(serbuff), 0);
        if(n < 0)
        {
            std::cerr << "recv err" << std::endl;
            break;
        }
        serbuff[n] = 0;
        std::cout << "server message# " << serbuff << std::endl;
    }

    ::close(sockfd);

    return 0;
}